﻿namespace Service.EF
{
    #region using

    using System;
    using System.Linq;
    using System.Transactions;
    using Model;

    #endregion

    public class TodoService : ITodoService, IDisposable
    {
        #region Constants and Fields

        private readonly TodoContext _db;

        #endregion

        #region Constructors and Destructors

        public TodoService()
        {
            _db = new TodoContext();
        }

        #endregion

        #region Public Methods

        public IQueryable<Todo> All()
        {
            return _db.Todos;
        }

        public void Delete(int todoId)
        {
                var toDelete = _db.Todos.SingleOrDefault(x => x.Id == todoId);
                _db.Todos.Remove(toDelete);
                _db.SaveChanges();
        }

        public void Update(Todo entity)
        {
                var toUpdate = _db.Todos.SingleOrDefault(x => x.Id == entity.Id);
                if(toUpdate != null)
                {
                    toUpdate.Title = entity.Title;
                    toUpdate.Done = entity.Done;
                }
                _db.SaveChanges();
        }

        public void Dispose()
        {
            if(_db != null) _db.Dispose();
        }

        public Todo Insert(Todo entity)
        {
            _db.Todos.Add(entity);
            _db.SaveChanges();
            return entity;
        }

        #endregion
    }
}